/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"8FB92BE9-B8AE-4C0D-B175-C82411AEBC14"}
 */
var fHtml = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"9F9B8B9F-8C17-4985-BA9F-295427ECB153"}
 */
var fEjeY = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"3A90651A-1B9A-4DE0-9B5E-029D130667D3"}
 */
var fEjeX = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"07A6B988-D2D2-41B5-8820-53346DA856C3"}
 */
var fTipoGrafico = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"6C14D8B7-6E2A-4689-A2CB-49A1DD1B37F9"}
 */
var fTitulo = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"EE2CD371-73EE-4CDF-9F02-4BA0D7479E5E"}
 */
var fResultado = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"2391A757-54EC-4887-9995-887F07AE9F2D",variableType:4}
 */
var fAnio = null;

/**
 * @type {Array}
 * 
 * @properties={typeid:35,uuid:"045C3868-15E1-4B9D-B9C2-552BF6ECB8B8",variableType:-4}
 */
var fResultados = new Array();

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"85875457-503E-4F54-AEA2-AF0B8F88101D"}
 */
function buscar(event) {
	
	if (!globals.gEnsayo || !fAnio || !fResultados)
	{
		globals.DIALOGS.showWarningDialog('Aviso','Por favor, complete todos los datos','OK')
		return
	}
	var $param = fResultados.map(function() {return "?"}).join(",")
	var query = 'SELECT COUNT (analisis_id) as "cant", resultado, date_part(\'year\',m.fecha) - date_part(\'year\',p.fecha_nacimiento) as "edad", '+
					'resultado || \' - \' || date_part(\'year\',m.fecha) - date_part(\'year\',p.fecha_nacimiento) || \' años\' as "key" '+
					'FROM analisis_dtl as "ad" '+
					'JOIN analisis_cab as "ac" ON ad.analisis_cab_id = ac.analisis_cab_id '+
					'JOIN muestra_destino as "md" ON md.muestra_destino_id = ac.muestra_destino_id '+
					'JOIN muestras as "m" ON m.muestra_id = md.muestra_id '+
					'JOIN pacientes as "p" ON p.paciente_id = m.paciente_id '+
					'WHERE ensayo_id = ? AND date_part(\'year\',m.fecha) = ? AND resultado IN ('+ $param+') AND m.fecha is not null AND p.fecha_nacimiento is not null AND ad.userv_id = ? '+
					'GROUP BY edad, resultado '+
					'ORDER BY resultado;'
	var max 			= -1
	var args 			= [globals.gEnsayo, fAnio]
	args 				= args.concat(fResultados)
	args[args.length]	= globals.gUservID 
	var ds 				= databaseManager.getDataSetByQuery('cepario',query,args,max)
	
	if (ds.getMaxRowIndex() == 0)
	{
		globals.DIALOGS.showWarningDialog('Aviso','No se encontraron muestras con esos datos','OK')
		return
	}
	/*
  	Barras|bvs
	Torta|pc
	Linea|lc
	*/
/*	if (fTipoGrafico == 'pc')
		plugins.jasperPluginRMI.runReport(ds,'cepario_ensres_torta.jasper',null,plugins.jasperPluginRMI.OUTPUT_FORMAT.VIEW, {pTitulo: fTitulo});
	else
	{
		
	}*/
	
	var $titulo = fTitulo
	while ($titulo && $titulo.indexOf(' ') != -1)
	{
		$titulo = $titulo.replace(' ','+')
	}
	
	var $url 		= 'https://chart.googleapis.com/chart?cht='+fTipoGrafico+'&chs=660x330&chxt=x,y,x,y&chbh=50&chtt='+$titulo
	var $colores 	= '1A1A66,2E2EB8,9999E6,EBEBFA'
	var $chm		= '&chm=N,EBEBFA,0,,12,,c|N,9999E6,1,,12,,c|N,2E2EB8,2,,12,,c|N,1A1A66,3,,12,,c'
	
	var $separador_ref 		= '|'
	/*
	  	Barras|bvs
		Torta|pc
		Linea|lc
	 */
	if (fTipoGrafico == 'bvs')
	{
		$url += $chm
	}
	else
	{
		if (fTipoGrafico == 'pc')
		{
			$separador_ref = '||||'
		}
		else
		{
			$url += $chm
		}
	}
	
	var $ref 	= '&chxl=2:|'+fEjeX+'|3:|'+fEjeY+'|0:|'
	var $data_t = '&chd=t:'
	var $data 	= ''
	var $leg 	= '&chdl='
	
	var $legends 	= ['0-1','2-3','4-6','%2B7']
	var $valores 	= [0,0,0,0]
	var $final		= new Array()
	var $cant 		= ds.getMaxRowIndex()
	var $totales	= new Array()
	var $total 		= 0
	var i 			= 1
	var $ref_val	= ''
	
	var $ds_final = databaseManager.createEmptyDataSet(0,['Resultado','Edad','Cantidad','Porcentaje'])
	
	/** @type {String}*/
	var $res_ant 	= ds.getValue(1,2)
	while (i <= $cant)
	{
		ds.rowIndex = i
		if ($res_ant != ds[2])
		{
			for (var k = 0 ; k < 4 ; k++)
			{
				$ds_final.addRow([$res_ant,$legends[k].replace('%2B','+'),$valores[k]])
			}
			
			$final.push($valores)
			$valores 	= [0,0,0,0]
			$totales.push($total)
			$total 		= 0
			$ref_val	+= $res_ant + $separador_ref
			$res_ant 	= ds[2]
			if (fTipoGrafico == 'pc')
			{
				$colores += ',' + $colores
			}
		}
		if (ds[3] <= 1)
		{
			var $col = 0
		}
		else
			if (ds[3] <= 3)
			{
				var $col = 1
			}
			else
				if (ds[3] <= 6)
				{
					var $col = 2
				}
				else
				{
					var $col = 3
				}
		$valores[$col] += ds[1]
		$total += ds[1]
		i++
	}
	
	for (var k = 0 ; k < 4 ; k++)
	{
		$ds_final.addRow([$res_ant,$legends[k].replace('%2B','+'),$valores[k]])
	}
	
	$ref_val += $res_ant
	$final.push($valores)
	$totales.push($total)
	
	var $limite_1 	= $final.length
	var $limite_2 	= 4
	var $j			= $limite_1
	var $k			= 1
	if (fTipoGrafico == 'bvs')
	{
		$limite_1 	= 4
		$limite_2 	= $final.length
		$j			= 1
		$k			= $limite_2
	}
	for (var j = 0 ; j < $limite_1 ; j++)
	{
		if (j != 0)
		{
			$data += '|'
		}
		for (var k = 0 ; k < $limite_2 ; k++)
		{
			var $dato
			var $total
			if (fTipoGrafico == 'bvs')
			{
				$dato = $final[k][j]
				$total = $totales[k]
			}
			else
			{
				$dato = $final[j][k]
				$total = $totales[j]
			}
			var $avg = $dato / $total * 100
			if (k != 0)
			{
				$data 	+= ','
			}
			var $porc = $avg.toFixed(2)
			if ($porc == null)
				$porc = 0
			$data 	+= $porc
			$ds_final.setValue(j*$j + k*$k +1,4,$porc)
		}
	}
	
	var $leg_val = $legends.join('|')
	/*
	  	Barras|bvs
		Torta|pc
		Linea|lc
	 */
	if (fTipoGrafico == 'bvs')
		$url += '&chco='+$colores + $data_t + $data + $ref + $ref_val + $leg + $leg_val
	else
	//SI LINEAS
		if (fTipoGrafico == 'lc')
			$url += '&chco='+$colores + $data_t + $data + $ref + $leg_val + $leg + $ref_val
		else
			$url += '&chco='+$colores + $data_t + $data + $ref + $ref_val + $leg + $leg_val
	elements.lbl.imageURL = $url
	fHtml = '<html>'+ ds.getAsHTML() +'</html>'
	//application.output($url)
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"5D2DFDA0-DBA9-4918-BB1E-2B59540BFCE7"}
 */
function imprimir(event) {
	var $name = 'estadisticas_1_imp'
	history.removeForm($name)
	solutionModel.removeForm($name)
	
	var $frm = solutionModel.cloneForm($name,solutionModel.getForm('estadisticas_1'))
	$frm.styleClass = 'impresion'
	var $cmp = $frm.getComponents()
	for (var i = 0 ; i < $cmp.length ; i++)
	{
		$cmp[i].styleClass = 'impresion'
	}
	forms[$name].controller.recreateUI()
	forms[$name].elements.lbl.imageURL = elements.lbl.imageURL
	forms[$name].fTitulo 	= fTitulo
	forms[$name].fResultado = fResultado
	forms[$name].fAnio 		= fAnio
	forms[$name].controller.showPrintPreview(true)
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"06EE0210-5E49-401D-AAE0-1C9E5B359BFA"}
 */
function iraResultados(event) {
	globals.formEnVentana('estadisticas_1_resultados','RESULTADOS','Elija los resultados')
}

/**
 * @properties={typeid:24,uuid:"B430AB1E-191C-4D22-B651-1FA4E1721EA2"}
 */
function xls() {
	if (!fHtml)
	{
		globals.DIALOGS.showWarningDialog('Aviso','No hay datos. Por favor, haga una consulta primero','OK')
		return
	}
	var $html = fHtml
	var fecha = application.getServerTimeStamp()
	fecha = utils.dateFormat(fecha,'dd-MM-yyyy hh-mm-ss')
	var $nombre = gidformactual_to_forms.titulo + ' ' + fecha + '.xls'
	if (application.getApplicationType() == APPLICATION_TYPES.WEB_CLIENT)
	{
		var jsFile = plugins.file.createFile($nombre)
	}
	else
	{
		var jsFile = plugins.file.showFileSaveDialog($nombre)
	}
	if (jsFile)
	{
		var fw = new Packages.java.io.FileWriter(jsFile.getAbsolutePath());
		var bw = new Packages.java.io.BufferedWriter(fw);
	
		bw.write($html,0,$html.length)
		bw.close()
		fw.close()
		
		if (application.getApplicationType() == APPLICATION_TYPES.WEB_CLIENT)
		{
			var mimeType = 'application/vnd.ms-excel'
			if (!plugins.file.writeFile(jsFile.getName(), jsFile.getBytes(), mimeType))
			{
				globals.DIALOGS.showErrorDialog('Error','Ocurrio un error y no se pudo grabar el archivo','OK');
			}
			plugins.file.deleteFile(jsFile.getAbsolutePath())
		}
		else
		{
			//application.showURL('file:///'+ jsFile.getAbsolutePath())
			application.executeProgram("rundll32.exe", ["url.dll,FileProtocolHandler", jsFile.getAbsolutePath()])
		}
	}
}

/**
 * @properties={typeid:24,uuid:"F6AF04B8-E2B8-4166-AC38-2202227FE1EF"}
 */
function csv() {
	globals.DIALOGS.showWarningDialog('Aviso','Opción no válida para esta pantalla. Por favor, exporte a XLS','OK')
}
